package com.minelx.treeftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

public class FileClient {

	private final FTPClient client;

	public FileClient(FTPClient client) {
		this.client = client;
	}

	public void read(OutputStream output, String path) {
		try {
			client.retrieveFile(path, output);
			output.flush();
		} catch (IOException e) {
			throw new RuntimeException("operation failed.", e);
		}
	}

	public String[] listFilesAt(String path) {
		try {
			String[] result = client.listNames(path);
			if (result != null) {
				return result;
			}
			return new String[0];
		} catch (IOException e) {
			throw new RuntimeException("operation failed.", e);
		}
	}

	public String[] listDirectoriesAt(String path) {
		try {
			return Arrays.stream(client.listDirectories(path))
					.filter(ftpFile -> !isSystemFile(ftpFile))
					.map(FTPFile::getName)
					.toArray(String[]::new);
		} catch (IOException e) {
			throw new RuntimeException("operation failed.", e);
		}
	}

	private boolean isSystemFile(FTPFile ftpFile) {
		return ftpFile.getName().equals(".") || ftpFile.getName().equals("..");
	}
}
